//pin 2 is DATA0
//pin 3 is DATA1

//Data0 is -- Pin 21 -- 2
//Data1 is -- Pin 20 -- 3

int grnLed = 7;

long previousMillis = 0;
int interval = 3000;

volatile unsigned long bit_holder = 0;
volatile int bit_count = 0;





void setup()
{
  Serial.begin(9600);

  clearinterrupts();

  attachInterrupt(2, DATA0, RISING);
  attachInterrupt(3, DATA1, RISING);
  delay(10);

  // digitalWrite(13, HIGH); // show Arduino has finished initilisation
  Serial.println("READER_0001");

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
  run();
}


void loop() 
{
}

void run()
{
  while(true)
  {
    getID();
  }
}

void getID()
{
  //clear buffer after timeout
  if (millis() - previousMillis > interval) {
    bit_count = 0; 
    bit_holder = 0;
    previousMillis = millis();
  }

  //full read resutlts in 35 bits
  if (bit_count == 35) {
    previousMillis = millis();

    //shift right so that result matches what is printed on the card
    bit_holder = bit_holder >> 1;

    //take only the lower 20 bits
    bit_holder &= 0xFFFFF;
    Serial.println(bit_holder);

    //turn green if card is accepted      
    if (bit_holder == 185360)
    {
      digitalWrite(13, HIGH);
      delay(3000);
      digitalWrite(13, LOW);
    }
    bit_count = 0; 
    bit_holder = 0;

    delay(10);
  }
  delay(50);
}



void clearinterrupts () {
  // the interrupt in the Atmel processor mises out the first negitave pulse as the inputs are already high,
  // so this gives a pulse to each reader input line to get the interrupts working properly.
  // Then clear out the reader variables.
  // The readers are open collector sitting normally at a one so this is OK
  for(int i = 2; i<4; i++){
    pinMode(i, OUTPUT);
    digitalWrite(i, HIGH); // enable internal pull up causing a one
    digitalWrite(i, LOW); // disable internal pull up causing zero and thus an interrupt
    pinMode(i, INPUT);
    digitalWrite(i, HIGH); // enable internal pull up
  }
  delay(10);
}

void DATA0(void) {
  bit_count++;
  bit_holder = bit_holder << 1;
}

void DATA1(void) 
{
  bit_count++;
  bit_holder = bit_holder << 1;
  bit_holder |= 1;
}



